package com.ruoyi.nsh.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.nsh.service.ChartService;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.nsh.config.ChartQueriesConfig;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@DataSource(value = DataSourceType.GBASE)
public class ChartServiceImpl implements ChartService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private ChartQueriesConfig chartQueriesConfig;
    
    @Cacheable(value = "chart", key = "#chartId + #params.toString()")
    public List<Map<String, Object>> getChartData(String chartId, Map<String, Object> params) {
        String sql = chartQueriesConfig.getQueries().get(chartId);
        if (sql == null) {
            throw new RuntimeException("Chart query not found: " + chartId);
        }
        
        // 处理SQL中的参数
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String value;
            if (entry.getValue() instanceof Number) {
                // 数字类型不加引号
                value = String.valueOf(entry.getValue());
            } else if (entry.getValue() instanceof Date) {
                // 日期类型加引号
                value = "'" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(entry.getValue()) + "'";
            } else {
                // 其他类型加引号
                value = "'" + String.valueOf(entry.getValue()) + "'";
            }
            sql = sql.replace("#{" + entry.getKey() + "}", value);
        }
        
        return jdbcTemplate.queryForList(sql);
    }
}